package cn.wyl.basic.service.impl;

import cn.wyl.basic.exception.BusinessException;
import cn.wyl.basic.service.IVerifyCodeService;
import cn.wyl.basic.util.SmsUtils;
import cn.wyl.basic.util.StrUtils;
import cn.wyl.basic.util.VerifyCodeUtils;
import cn.wyl.user.domain.User;
import cn.wyl.user.mapper.UserMapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
public class VerifyCodeServiceImpl implements IVerifyCodeService {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private UserMapper userMapper;

    @Override
    public String getImageCode(String key) {
        //通过StrUtils生成4位的图形验证码code --字符串
        String code = StrUtils.getComplexRandomString(4);
        //将key和图形验证码code保存到Redis，5分钟后过期
        redisTemplate.opsForValue().set(key,code,5, TimeUnit.MINUTES);
        //将图形验证码写到图片中并且使用base64编码
        String base64Str = VerifyCodeUtils.verifyCode(115,40,code);
        return base64Str;
    }

    @Override
    public void getSmsCode(Map<String, String> map) {
        String phone = map.get("phone");
        String imageCode = map.get("imageCode");
        String imageCodeKey = map.get("imageCodeKey");
        //1.空值校验
        if(StringUtils.isEmpty(phone) || StringUtils.isEmpty(imageCode)){
            throw new BusinessException("信息不能为空");
        }
        //2.校验 - 图形验证码是否过期
        Object obj = redisTemplate.opsForValue().get(imageCodeKey);
        if(obj==null){
            throw new BusinessException("图形验证码过期");
        }
        if(!imageCode.equalsIgnoreCase(obj.toString())){
            throw new BusinessException("图形验证码错误");
        }
        //3.校验 - 手机验证码是否注册过
        User user = userMapper.findByPhone(phone);
        if(user != null){
            throw new BusinessException("该手机已经注册");
        }

        //4.获取手机验证码【register:电话 - 9527（验证码）:时间戳】
        Object phoneCodeObj = redisTemplate.opsForValue().get("register:" + phone);
        String code = null;
        if(phoneCodeObj == null){//第一次发送验证码，或者验证码已过期
            code = StrUtils.getRandomString(6);
        }else {
            //上一次获取验证码的时间戳
            long oldTime = Long.parseLong(phoneCodeObj.toString().split(":")[1]);
            //当前时间戳
            long newTime = System.currentTimeMillis();
            if((newTime-oldTime)<1*60*1000){//一分钟内重复请求获取验证码
                throw new BusinessException("请勿重复获取验证码");
            }
            code = phoneCodeObj.toString().split(":")[0];
        }
        //5.将验证码保存到Redis，3分钟有效
        redisTemplate.opsForValue().set("register:"+phone,code+":"+System.currentTimeMillis(),3,TimeUnit.MINUTES);
        //6.向手机发送验证码
        //SmsUtils.sendSms(phone,"验证码:"+code+",请在3分钟内使用！");
        System.out.println("验证码:" + code + ",请在3分钟内使用！");

    }

    @Override
    public void binderSmsCode(Map<String, String> map) {
        String phone = map.get("phone");
        //1.空值校验
        if(StringUtils.isEmpty(phone)){
            throw new BusinessException("信息不能为空");
        }
        //2.获取手机验证码【binder:电话 - 9527（验证码）:时间戳】
        Object phoneCodeObj = redisTemplate.opsForValue().get("binder:" + phone);
        String code = null;
        if(phoneCodeObj == null){//第一次发送验证码，或者验证码已过期
            code = StrUtils.getRandomString(6);
        }else {
            //上一次获取验证码的时间戳
            long oldTime = Long.parseLong(phoneCodeObj.toString().split(":")[1]);
            //当前时间戳
            long newTime = System.currentTimeMillis();
            if((newTime-oldTime)<1*60*1000){//一分钟内重复请求获取验证码
                throw new BusinessException("请勿重复获取验证码");
            }
            code = phoneCodeObj.toString().split(":")[0];
        }
        //5.将验证码保存到Redis，3分钟有效
        redisTemplate.opsForValue().set("binder:"+phone,code+":"+System.currentTimeMillis(),3,TimeUnit.MINUTES);
        //6.向手机发送验证码
        //SmsUtils.sendSms(phone,"验证码:"+code+",请在3分钟内使用！");
        System.out.println("验证码:" + code + ",请在3分钟内使用！");
    }
}
